
import { useLocation } from 'react-router';
import Styles from './index.module.css'
import { useEffect, useRef, useState } from 'react';
import { Button, Space } from 'antd';
import { flushSync } from 'react-dom';
import TestImage from './components/TestImage';
import axios from 'axios';
import {
  connWebSocket,
  // serverfun
} from '@/utils/index'

export default function Team() {
  const locationInfo = useLocation();

  const [count, setCount] = useState(0);
  const socketRef = useRef<any>(null)
  const testRef = useRef<{
    sendMessage: () => number
  } | null>(null)

  const [listData, setListData] = useState([]);

  const addCount = () => {
    // const aa = testRef.current?.sendMessage();
    // console.log('--', aa);

  }

  const flushAddCount = () => {
    flushSync(() => {
      setCount(count + 1);
      console.log('add1', count);
      setCount(count + 1);
      console.log('add2', count);
    })
  }

  // useEffect(() => {
  //   console.log('effect', count);// 至打印一次
  // }, [count])

  useEffect(() => {
    axios.get(`${location.origin}/api/bigData/list`).then(({ data }) => {
      // console.log('data', data);
      setListData(data?.data?.list || [])
    })


    // console.log(import.meta.url);
    // serverfun()
    conn();

    return () => {
      // 清理函数，在组件卸载时关闭 WebSocket 连接
      if (socketRef.current) {
        socketRef.current.close();
        socketRef.current = null;

      }

    }

  }, [])

  const conn = () => {
    socketRef.current = connWebSocket()
    socketRef.current.onopen = () => {
      console.log('websocket已连接');
    }
    socketRef.current.onmessage = (message: any) => {
      console.log('socket-onmessage', message);
    }

    socketRef.current.onclose = (event: any) => {
      console.log('socket-onclose', event);

    };

  }

  const sendSocket = () => {
    socketRef.current.send('客户端：向服务端发送数据')
  }

  return (
    <div className={Styles.container}>
      {/* 标题 */}
      <div className={Styles.title}>{locationInfo?.state?.title || 'Team'}</div>

      {/* 内容模块 */}
      <div className={Styles.mainContent}>

        <div className={Styles.content}>

          <ul>
            {
              listData?.map((item: any) => (
                <li key={item.id}>
                  <span>{item.id} : </span> {item.name}
                </li>
              ))
            }

          </ul>

          <div className={Styles.middleContent}>
            <div className={Styles.tooltips}>
              <TestImage ref={testRef} />
            </div>
          </div>


        </div>



        <div className={Styles.fixedBox}>
          <Space direction="vertical" >
            <Button type='primary' onClick={addCount}>父组件调用子组件方法</Button>
            <Button type='primary' onClick={flushAddCount}>执行useState同步更新</Button>
            <Button type='primary' onClick={sendSocket}>向服务端发送消息</Button>
          </Space>
        </div>
      </div>
    </div>
  )
}